<template>
  <div class="book-management">
    <div class="header">
      <h2>图书管理</h2>
      <el-button type="primary" @click="showAddDialog">添加图书</el-button>
    </div>

    <el-table 
      :data="books" 
      style="width: 100%" 
      v-loading="loading"
    >
      <el-table-column prop="isbn" label="ISBN" width="120" />
      <el-table-column prop="title" label="书名" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="publisher" label="出版社" width="120" />
      <el-table-column prop="price" label="价格" width="80">
        <template #default="{ row }">
          ￥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="库存" width="80" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            size="small"
            @click="editBook(row)"
          >
            编辑
          </el-button>
          <el-button 
            size="small" 
            type="danger"
            @click="deleteBook(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 详情 Dialog -->
    <el-dialog v-model="dialogVisible" title="图书详情">
      <el-form :model="selectedBook" label-width="100px">
        <el-form-item label="ISBN">
          <el-input v-model="selectedBook.isbn" disabled />
        </el-form-item>
        <el-form-item label="书名">
          <el-input v-model="selectedBook.title" disabled />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="selectedBook.author" disabled />
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="selectedBook.publisher" disabled />
        </el-form-item>
       
        <el-form-item label="入库日期">
          <el-input v-model="selectedBook.date" disabled />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model="selectedBook.quantity" disabled />
        </el-form-item>
        <el-form-item label="定价">
          <el-input v-model="selectedBook.price" disabled />
        </el-form-item>
        <el-form-item label="进货折扣">
          <el-input v-model="selectedBook.purchase_discount" disabled />
        </el-form-item>
        <el-form-item label="销售折扣">
          <el-input v-model="selectedBook.sales_discount" disabled />
        </el-form-item>
        <el-form-item label="进货渠道">
          <el-input v-model="selectedBook.channel" disabled />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="selectedBook.notes" disabled />
        </el-form-item>
        <el-form-item label="出版日期">
          <el-input v-model="selectedBook.publish_date" disabled />
        </el-form-item>
        <el-form-item label="版本">
          <el-input v-model="selectedBook.version" disabled />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 修改 Dialog -->
    <el-dialog v-model="editDialogVisible" title="修改图书信息">
      <el-form :model="editBookForm" label-width="100px">
        <el-form-item label="ISBN">
          <el-input v-model="editBookForm.isbn" disabled />
        </el-form-item>
        <el-form-item label="书名">
          <el-input v-model="editBookForm.title" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="editBookForm.author" />
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="editBookForm.publisher" />
        </el-form-item>
        
        <el-form-item label="入库日期">
          <el-date-picker v-model="editBookForm.date" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input-number v-model="editBookForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="定价">
          <el-input-number v-model="editBookForm.price" :min="0" :step="0.01" />
        </el-form-item>
        <el-form-item label="进货折扣">
          <el-input-number v-model="editBookForm.purchase_discount" :min="0.1" :max="1"  :step="0.01"/>
        </el-form-item>
        <el-form-item label="销售折扣">
          <el-input-number v-model="editBookForm.sales_discount" :min="0.1" :max="1" :step="0.01"/>
        </el-form-item>
        <el-form-item label="进货渠道">
          <el-input v-model="editBookForm.channel" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editBookForm.notes" />
        </el-form-item>
        <el-form-item label="出版日期">
          <el-date-picker v-model="editBookForm.publish_date" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="版本">
          <el-input v-model="editBookForm.version" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveBook">保存</el-button>
      </span>
    </el-dialog>

    <!-- 添加图书 Dialog -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="添加图书"
      width="60%"
    >
      <el-form :model="bookForm" label-width="100px">
        <el-form-item label="ISBN">
          <el-input v-model="bookForm.isbn" />
        </el-form-item>
        <el-form-item label="书名">
          <el-input v-model="bookForm.title" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="bookForm.author" />
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="bookForm.publisher" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input-number v-model="bookForm.price" :min="0" :step="0.01" />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input-number v-model="bookForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="经销商">
          <el-select 
            v-model="bookForm.dealer_id"
            placeholder="请选择经销商"
            filterable
            :loading="dealersLoading"
          >
            <el-option
              v-for="dealer in dealers"
              :key="dealer.id"
              :label="dealer.name"
              :value="dealer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进货折扣">
          <el-input-number 
            v-model="bookForm.purchase_discount" 
            :min="0.1" 
            :max="1" 
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="销售折扣">
          <el-input-number 
            v-model="bookForm.sales_discount" 
            :min="0.1" 
            :max="1" 
            :step="0.01"
          />
        </el-form-item>
        <el-form-item label="入库日期">
          <el-date-picker v-model="bookForm.date" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="出版日期">
          <el-date-picker v-model="bookForm.publish_date" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="版本">
          <el-input v-model="bookForm.version" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBook" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import BookService from '@/api/bookService'
import DealerService from '@/api/dealerService'

const books = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const selectedBook = ref({})
const editBookForm = ref({})
const dealers = ref([])
const dealersLoading = ref(false)
const addDialogVisible = ref(false)
const submitting = ref(false)

const bookForm = ref({
  isbn: '',
  title: '',
  author: '',
  publisher: '',
  price: 0,
  quantity: 1,
  dealer_id: '',
  purchase_discount: 1,
  sales_discount: 1,
  // ... 其他字段
})

// 获取图书列表
const fetchBooks = async () => {
  loading.value = true
  try {
    const response = await BookService.getAllBooks()
    books.value = response.data
    console.log('Fetched books:', books.value)
  } catch (error) {
    console.error('Error fetching books:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

const viewDetails = (book) => {
  selectedBook.value = { ...book }
  dialogVisible.value = true
}

const editBook = (book) => {
  editBookForm.value = { ...book }
  editDialogVisible.value = true
}

const saveBook = async () => {
  try {
    // 这里假设你有一个更新图书信息的API
    const response = await BookService.updateBook(editBookForm.value.id, editBookForm.value)
    console.log('Book updated:', response.data)
    fetchBooks() // 更新图书列表
    editDialogVisible.value = false // 关闭修改 Dialog
  } catch (error) {
    console.error('更新图书信息失败:', error)
  }
}

const deleteBook = async (book) => {
  try {
    await BookService.deleteBook(book.id)
    fetchBooks()
    ElMessage.success('图书删除成功')
  } catch (error) {
    console.error('删除图书失败:', error)
    ElMessage.error('删除图书失败')
  }
}

// 获取经销商列表
async function fetchDealers() {
  dealersLoading.value = true
  try {
    console.log('BookManagement: Fetching dealers...')
    const response = await DealerService.getAllDealers()
    console.log('BookManagement: Dealers response:', response)
    if (response.data && Array.isArray(response.data)) {
      dealers.value = response.data
      console.log('BookManagement: Dealers loaded:', dealers.value)
    } else {
      throw new Error('Invalid dealers data format')
    }
  } catch (error) {
    console.error('BookManagement: Error fetching dealers:', error)
    ElMessage.error('获取经销商列表失败')
    dealers.value = []
  } finally {
    dealersLoading.value = false
  }
}

// 显示添加对话框
function showAddDialog() {
  bookForm.value = {
    isbn: '',
    title: '',
    author: '',
    publisher: '',
    price: 0,
    quantity: 1,
    dealer_id: '',
    purchase_discount: 1,
    sales_discount: 1,
    // ... 其他字段重置
  }
  addDialogVisible.value = true
}

// 提交图书
async function submitBook() {
  if (!bookForm.value.isbn || !bookForm.value.title) {
    ElMessage.warning('请填写必要信息')
    return
  }

  submitting.value = true
  try {
    await BookService.addBook(bookForm.value)
    ElMessage.success('添加图书成功')
    addDialogVisible.value = false
    fetchBooks() // 刷新图书列表
  } catch (error) {
    console.error('Error adding book:', error)
    ElMessage.error('添加图书失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  fetchBooks()
  fetchDealers() // 获取经销商列表
})
</script>

<style scoped>
.book-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.el-table {
  background-color: #fff;
}

.el-table-column {
  text-align: center;
}
</style>
  